package com.iemes.controller.finance;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.MaterialWangJiaFormMap;
import com.iemes.entity.SalesPriceApprovalFormMap;
import com.iemes.mapper.finance.MaterialWangJiaMapper;
import com.iemes.mapper.finance.SalesPriceApprovalMapper;
import com.iemes.plugin.PageView;
import com.iemes.util.Common;
import com.iemes.util.ExcelUtil;

@RequestMapping("/finance")
@Controller
public class MaterialWangJiaController extends BaseController{

	@Inject
	private MaterialWangJiaMapper materialWangJiaMapper;
	
	@Inject
	private SalesPriceApprovalMapper salesPriceApprovalMapper;
	
	
	@RequestMapping("materialwangjia")
	public String loss(Model model){
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/finance/receivablesmanagement/materialwangjia_list";
	}
	
	@RequestMapping("materialwangjia_sub")
	public String sub(Model model,HttpSession session){
		//点击计算，数据显示在页面上
		//MaterialWangJiaFormMap materialWangJiaFormMap=getFormMap(MaterialWangJiaFormMap.class);
		List<Map<String,Object>> materialWangJiaFormMaps=(List<Map<String, Object>>) session.getAttribute("materialWangJiaFormMaps");
		double total1 = 0,total2=0,total3=0,total4=0,total5=0,totalAverage=0;
		for(Map<String,Object>map:materialWangJiaFormMaps){
			total1+=Double.parseDouble(map.get("supplierprice1").toString());
			total2+=Double.parseDouble(map.get("supplierprice2").toString());
			total3+=Double.parseDouble(map.get("supplierprice3").toString());
			total4+=Double.parseDouble(map.get("supplierprice4").toString());
			total5+=Double.parseDouble(map.get("supplierprice5").toString());
		}
		System.out.println("aa"+total1);
		System.out.println("bb"+total2);
		System.out.println("cc"+total3);
		System.out.println("dd"+total4);
		System.out.println("ee"+total5);
		model.addAttribute("total1", total1);
		model.addAttribute("total2", total2);
		model.addAttribute("total3", total3);
		model.addAttribute("total4", total4);
		model.addAttribute("total5", total5);
		//总均价
		totalAverage=(total1+total2+total3+total4+total5)/5;
		model.addAttribute("totalAverage", totalAverage);
		return Common.BACKGROUND_PATH + "/finance/receivablesmanagement/materialwangjia_sub";
	}
	
	@ResponseBody
	@RequestMapping("materialwangjia_addEntity")
//	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="价格审批",methods="价格审批-添加")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity(HttpServletRequest request) throws Exception {
		SalesPriceApprovalFormMap salesPriceApprovalFormMap=getFormMap(SalesPriceApprovalFormMap.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		salesPriceApprovalFormMap.put("date", sdf.format(date));
		
		//泰源辅料总和、客户辅料总和、泰源总价、客户总价
		double taiyuanIngredients=0,customerIngredients=0,taiyuanEpsTotal=0,customerEpsTotal=0;
		
		//获取泰源辅料
		String[] tIngredients = request.getParameterValues("salesPriceApprovalFormMap.taiyuanIngredients");
		System.out.println(tIngredients.length);
		//获取客户辅料
		String[] cIngredients = request.getParameterValues("salesPriceApprovalFormMap.customerIngredients");
		System.out.println(cIngredients.length);
		//循环叠加
		if(null != tIngredients ){
			for(int i=0;i<tIngredients.length;i++){
				System.out.println("大大");
				System.out.println("泰源："+tIngredients[i]);
				taiyuanIngredients+=Double.parseDouble(tIngredients[i]);
			}
		}
		
		if(null != cIngredients ){
			for(int i=0;i<cIngredients.length;i++){
				System.out.println("小小");
				System.out.println("客户："+cIngredients[i]);
				customerIngredients+=Double.parseDouble(cIngredients[i]);
			}
		}
		salesPriceApprovalFormMap.put("taiyuanIngredients", taiyuanIngredients);
		salesPriceApprovalFormMap.put("customerIngredients", customerIngredients);
		//泰源总价
		taiyuanEpsTotal=Double.parseDouble(request.getParameter("salesPriceApprovalFormMap.taiyuanEps"))+taiyuanIngredients;
		System.out.println("泰eps"+request.getParameter("salesPriceApprovalFormMap.taiyuanEps"));
		System.out.println("客eps"+request.getParameter("salesPriceApprovalFormMap.customerEps"));
		//客户总价
		customerEpsTotal=Double.parseDouble(request.getParameter("salesPriceApprovalFormMap.customerEps"))+customerIngredients;
		System.out.println("泰源辅总"+taiyuanIngredients);
		System.out.println("客户辅总"+customerIngredients);
		System.out.println("泰源总"+taiyuanEpsTotal);
		System.out.println("客户总"+customerEpsTotal);
		
		salesPriceApprovalFormMap.put("taiyuanTotalPrice", taiyuanEpsTotal);
		salesPriceApprovalFormMap.put("customerTotalPrice", customerEpsTotal);
		salesPriceApprovalFormMap.put("state", 0);
		salesPriceApprovalMapper.addEntity(salesPriceApprovalFormMap);
		return "success";
	}
	
	
	@ResponseBody
	@RequestMapping("materialwangjia2_addEntity")
//	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="价格审批",methods="价格审批-添加")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity2(HttpServletRequest request) throws Exception {
		SalesPriceApprovalFormMap salesPriceApprovalFormMap=getFormMap(SalesPriceApprovalFormMap.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		salesPriceApprovalFormMap.put("date", sdf.format(date));
		
		//泰源辅料总和、泰源总价
		double taiyuanIngredients=0,taiyuanEpsTotal=0;
		
		//获取泰源辅料
		String[] tIngredients = request.getParameterValues("salesPriceApprovalFormMap.taiyuanIngredients");
		
		//循环叠加
		if(null != tIngredients ){
			for(int i=0;i<tIngredients.length;i++){
				taiyuanIngredients+=Double.parseDouble(tIngredients[i]);
			}
		}
		
		salesPriceApprovalFormMap.put("taiyuanIngredients", taiyuanIngredients);
		//泰源总价
		taiyuanEpsTotal=Double.parseDouble(request.getParameter("salesPriceApprovalFormMap.taiyuanEps"))+taiyuanIngredients;
		
		salesPriceApprovalFormMap.put("taiyuanTotalPrice", taiyuanEpsTotal);
		salesPriceApprovalFormMap.put("state", 0);
		salesPriceApprovalMapper.addEntity(salesPriceApprovalFormMap);
		return "success";
	}
	
	
	@ResponseBody
	@RequestMapping("materialwangjia_findByPage")
	public PageView findByPage(String pageNow, String pageSize,Model model,HttpSession session,HttpServletRequest request) throws Exception 
	{
		System.out.println(request.getParameter("materialWangJiaFormMap.begin"));
		MaterialWangJiaFormMap materialWangJiaFormMap=getFormMap(MaterialWangJiaFormMap.class);
		List<Map<String,Object>> materialWangJiaFormMaps=materialWangJiaMapper.getMaterialWangJiaByCondition(materialWangJiaFormMap);
		session.setAttribute("materialWangJiaFormMaps", materialWangJiaFormMaps);
		LuogicPaging(pageNow, pageSize, materialWangJiaFormMaps);
		return pageView;
	}
	

	@ResponseBody
	@RequestMapping(value="materialwangjia_deleteEntity")
	@SystemLog(module="原料网报价格",methods="原料网报价格-删除")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		MaterialWangJiaFormMap materialWangJiaFormMap=getFormMap(MaterialWangJiaFormMap.class);
		String[] ids = getParaValues("ids");
		String arr=ids[0];
		System.out.println("连着的："+arr);
		String[] str=arr.split(",");
		for(int i=0;i<str.length;i++){
			System.out.println("给我分开："+str[i]);
			materialWangJiaFormMap.put("state", 1);
			materialWangJiaFormMap.put("id", str[i]);
			baseMapper.editEntity(materialWangJiaFormMap);
		}
		return "success";
	}
	
	
	
	@ResponseBody
	@RequestMapping(value = "category_exportEntity")
	@SystemLog(module = "原料报价", methods = "财务-导出原料报价")// 凡需要处理业务逻辑的.都需要记录操作日志
	public String exportEntity(HttpServletResponse response,HttpServletRequest request) throws Exception {
		Connection conn = ExcelUtil.getConnection();
		try {
		PreparedStatement ps = conn
				.prepareStatement("SELECT * FROM `erp_materialwangjia`");
		ResultSet rs = ps.executeQuery();		
		//标题
		String title[] = { "编号" , "日期" , "无锡兴达EPS", "江阴龙王EPS" , "aa" , "bb" , "cc" ,  "状态"};
		// excel文件名
		String fileName =".xls";
		ExcelUtil.fillExcelData(request,response,rs, title ,fileName);
		
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (conn!=null) {
				conn.close();
			}
			
		}

		return "success";
	}
	
	
	
	
	
	@ResponseBody
	@RequestMapping(value = "excel", method = RequestMethod.POST)
	@SystemLog(module = "原料报价", methods = "财务-导入原料报价")
	public String uploadExcel(
			@RequestParam(value = "attachs", required = false) MultipartFile attachs,
			HttpServletRequest request) {
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;
		MaterialWangJiaFormMap materialWangJiaFormMap=getFormMap(MaterialWangJiaFormMap.class);
		try {
			fs = new POIFSFileSystem(attachs.getInputStream());
			wb = new HSSFWorkbook(fs);
			 // Excel的页签数量
            int sheet_size = wb.getNumberOfSheets();
			
		    for (int index = 0; index < sheet_size; index++) {
				HSSFSheet hssfSheet = wb.getSheetAt(index);// 获取第一个Sheet页
				if (hssfSheet != null) {
					for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
						HSSFRow hssfRow = hssfSheet.getRow(rowNum);
						if (hssfRow == null) {
							continue;
						}
						
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						
						materialWangJiaFormMap.set("date",
								ExcelUtil.formatCell(hssfRow.getCell(1)));
						materialWangJiaFormMap.set("supplierprice1",
								ExcelUtil.formatCell(hssfRow.getCell(2)));
						materialWangJiaFormMap.set("supplierprice2",
								ExcelUtil.formatCell(hssfRow.getCell(3)));
						materialWangJiaFormMap.set("supplierprice3",
								ExcelUtil.formatCell(hssfRow.getCell(4)));
						materialWangJiaFormMap.set("supplierprice4",
								ExcelUtil.formatCell(hssfRow.getCell(5)));
						materialWangJiaFormMap.set("supplierprice5",
								ExcelUtil.formatCell(hssfRow.getCell(6)));
						materialWangJiaFormMap.set("state",
								ExcelUtil.formatCell(hssfRow.getCell(7)));
						materialWangJiaMapper.addEntity(materialWangJiaFormMap);
						materialWangJiaFormMap.clear();
					}
				}
				
			}			
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "success";
	}
	
	
	
}
